import { useCallback, forwardRef, useImperativeHandle, memo, useReducer, useState } from "react";
import formreducer from './formreducer'
import { FormProvider } from "../common/context";
const Form = forwardRef((props, ref) => {
    const { onSubmit, children, initialValue } = props;
    const [state, dispatch] = useReducer(formreducer, initialValue || {})
    const [submitAction, setSubmitAction] = useState(false)
    useImperativeHandle(ref, () => ({
        formDataSubmit() {
            const values = Object.values(state);
            const flagSubmit = values.reduce((pre, current) => {
                return !!pre && !!current;
            });
            flagSubmit || setSubmitAction(true)
            onSubmit(state, flagSubmit);
        },
        onReset: onReset,
    }))
    const onReset = useCallback(() => {
        dispatch({
            type: 'formChange',
            payload: {
                ...initialValue,
            }
        })
    }, [initialValue])
    return (
        <FormProvider value={{
            state,
            dispatch,
            submitAction
        }}>
            {children}
        </FormProvider>
    )
})
export default memo(Form)